package com.atguigu.gmall.app.dwd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.ververica.cdc.connectors.mysql.MySQLSource;
import com.alibaba.ververica.cdc.connectors.mysql.table.StartupOptions;
import com.alibaba.ververica.cdc.debezium.DebeziumSourceFunction;
import com.alibaba.ververica.cdc.debezium.StringDebeziumDeserializationSchema;
import com.atguigu.gmall.bean.TableProcess;
import com.atguigu.gmall.func.DimSink;
import com.atguigu.gmall.func.MyDebeziumDeserializationSchema;
import com.atguigu.gmall.func.TableProcessFunction;
import com.atguigu.gmall.utils.MyKafkaUtil;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.streaming.api.datastream.*;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;
import org.apache.flink.streaming.connectors.kafka.KafkaSerializationSchema;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;
import org.apache.kafka.clients.producer.ProducerRecord;

import javax.annotation.Nullable;
import java.util.Properties;

/**
 * Created on 2021/11/5.
 *
 * @author ${AUTHOR}
 */
public class BaseDBApp {
    public static void main(String[] args) throws Exception {
        //TODO 1.基本环境准备
        //1.1 流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //1.2 设置并行度
        env.setParallelism(4);
        /*
        //TODO 2.检查点相关的设置
        //2.1 开启检查点
        env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);
        //2.2 设置检查点超时时间
        env.getCheckpointConfig().setCheckpointTimeout(60000L);
        //2.3 取消job的时候，检查点是否保留
        env.getCheckpointConfig().enableExternalizedCheckpoints(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
        //2.4 设置重启策略
        env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3,3000L));
        //2.5 设置状态后端
        env.setStateBackend(new FsStateBackend("xxxx"));
        //2.6 设置操作hadoop的用户
        System.setProperty("HADOOP_USER_NAME","atguigu");
        */
        //TODO 3.从Kafka主题中读取业务流数据
        String topic = "ods_base_db_m";
        String groupId = "base_db_app_group";

        FlinkKafkaConsumer<String> kafkaSource = MyKafkaUtil.getKafkaSource(topic, groupId);

        DataStreamSource<String> kafkaDS = env.addSource(kafkaSource);
        SingleOutputStreamOperator<JSONObject> jsonObjDs = kafkaDS.map(JSON::parseObject);
        //TODO 5.对流中的数据进行简单的ETL
        SingleOutputStreamOperator<JSONObject> filterDS = jsonObjDs.filter(
                new FilterFunction<JSONObject>() {
                    @Override
                    public boolean filter(JSONObject jsonObj) throws Exception {
                        boolean flag = jsonObj.getString("table") != null
                                && jsonObj.getString("table").length() > 0
                                && jsonObj.getJSONObject("data") != null
                                && jsonObj.getString("data").length() > 3;
                        return flag;
                    }
                }
        );
        jsonObjDs.print("jsonObjDs");

        //TODO 6.使用FlinkCDC读取配置表数据
        //6.1 创建mysqlSourceFunction
        DebeziumSourceFunction<String> mySQLSourceFunction = MySQLSource.<String>builder()
                .hostname("hadoop102")
                .port(3306)
                .databaseList("gmall0519_realtime")
                .tableList("gmall0519_realtime.table_process")
                .username("root")
                .password("123456")
                .startupOptions(StartupOptions.initial())
                .deserializer(new MyDebeziumDeserializationSchema())
                .build();


        DataStreamSource<String> mySQLDS = env.addSource(mySQLSourceFunction);
        MapStateDescriptor<String, TableProcess> mapStateDescriptor = new MapStateDescriptor<>("mapStateDescriptor", String.class, TableProcess.class);

        BroadcastStream<String> broadcastDS = mySQLDS.broadcast(mapStateDescriptor);
        BroadcastConnectedStream<JSONObject, String> connectDS = filterDS.connect(broadcastDS);

        OutputTag<JSONObject> dimTag = new OutputTag<JSONObject>("dimTag"){};
        SingleOutputStreamOperator<JSONObject> realDS = connectDS.process(
                new TableProcessFunction(dimTag,mapStateDescriptor)
        );
        DataStream<JSONObject> dimDS = realDS.getSideOutput(dimTag);

        dimDS.print("dimDS");
        realDS.print("realDS");

        dimDS.addSink(new DimSink());

        realDS.addSink(MyKafkaUtil.getKafkaSinkBySchema(new KafkaSerializationSchema<JSONObject>() {
            @Override
            public ProducerRecord<byte[], byte[]> serialize(JSONObject jsonObj, @Nullable Long timestamp) {
                String topic = jsonObj.getString("sink_table");
                return new ProducerRecord<byte[], byte[]>(topic,jsonObj.getJSONObject("data").toJSONString().getBytes());
            }
        }));
        env.execute();


    }
}
